package com.scf.contract.controller;

import com.aliyun.oss.OSSClient;
import com.scf.contract.entity.Appendix;
import com.scf.contract.service.FileService;
import com.scf.uitl.ResponseResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;



/**
 * @author author
 * @create 2021-11-17-10:10
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    FileService fileService;
    private OSSClient ossClient;  //oss客户端
    private static final String BUCKETNAME = "caimingfeng1105"; //桶名
    private static final String BASEPATH = "https://caimingfeng1105.oss-cn-beijing.aliyuncs.com/"; //阿里云网络路径
    ResponseResult responseResult = new ResponseResult();

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file){
        //获取到的文件名字
        String fileName = file.getOriginalFilename();
        //得到的后缀名
        String suffix = fileName.substring(fileName.indexOf("."));
        //新名字
        fileName = UUID.randomUUID().toString()+suffix;
        System.out.println(fileName);

        //上传文件
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();

            //设置上传的参数
            ossClient.putObject(BUCKETNAME, fileName, inputStream);

            //设置文件的过期时间   付费的不需要设置
            Date date = new Date(System.currentTimeMillis()+ 1000 * 60 * 60 * 24 * 30);
            //上传文件
            ossClient.generatePresignedUrl(BUCKETNAME,fileName,date);
            Appendix appendix = new Appendix(0,fileName,BASEPATH+fileName);
            int upload = fileService.upload(appendix);
            //返回数据
            Appendix fileResult = new Appendix();

            //返回结果

            fileResult.setAname(fileName);
            fileResult.setAurl(BASEPATH+fileName);

            responseResult.setCode(200);
            responseResult.setMessage("上传成功");
            responseResult.setData(fileResult);

            return responseResult;
        }catch (Exception e){
            e.printStackTrace();
        }
        return responseResult;
    }
    //删除文件
    @GetMapping("/del")
    public ResponseResult del(String fileName){
        ossClient.deleteObject(BUCKETNAME,fileName);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setMessage("删除成功！");
        return responseResult;
    }

    //查看所有图片
    @GetMapping("/allFile")
    public ResponseResult allFile(){
        List<Appendix> appendices = fileService.allFile();
        responseResult.setData(appendices);
        return responseResult;
    }
}

